//
//  HomeCollectionHeaderView.m
//  AffectionBee
//
//  Created by 李通 on 16/8/20.
//  Copyright © 2016年 chivalrous. All rights reserved.
//

#import "HomeCollectionHeaderView.h"
#import "IconButton.h"
#import "DisplayScroll.h"
#import "IconsAndActivitiesModel.h"

#define kMargin (20)
#define kButtonCount (4)
#define kButtonHeight (kButtonWidth + 10)
#define kButtonWidth ((self.bounds.size.width - kMargin * (kButtonCount + 1))/kButtonCount)

@interface HomeCollectionHeaderView ()<UIScrollViewDelegate>

@property (nonatomic,weak) DisplayScroll *scrollView;

@property (nonatomic,weak) UIView *bottomView;

@property (nonatomic,weak) UIPageControl *pageControl;

@property (nonatomic,weak) IconButton *button;

@property (nonatomic,strong) NSTimer *timer;

@end

@implementation HomeCollectionHeaderView

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        [self setContentControl];
        
        [self setupTimer];
        
        self.backgroundColor = [UIColor whiteColor];
    }
    return self;
}

- (void)setContentControl {
    //实例化ScrollView
    DisplayScroll *scrollView = [[DisplayScroll alloc]initWithFrame:CGRectMake(0, 0, kScreenSize.width, self.frame.size.height - kButtonHeight)];
    self.scrollView = scrollView;
    self.scrollView.delegate = self;
    [self addSubview:scrollView];
    
    //实例化pageControl
    UIPageControl *pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(kScreenSize.width - 100, scrollView.frame.size.height - 30, 100, 30)];
    self.pageControl = pageControl;
    [self addSubview:pageControl];
    pageControl.numberOfPages = kPageCount;
    pageControl.currentPage = 0;
    pageControl.pageIndicatorTintColor = [UIColor whiteColor];
    pageControl.currentPageIndicatorTintColor = [UIColor orangeColor];
    
    //实例化iconButton
    UIView *bottomView = [[UIView alloc]init];
    self.bottomView = bottomView;
    for (int i = 0; i < kButtonCount; i++) {
        
        IconButton *button = [[IconButton alloc]initWithFrame:CGRectMake(kMargin + kMargin * i + kButtonWidth * i, 0, kButtonWidth, kButtonHeight)];
        button.tag = i;
        [button addTarget:self action:@selector(didClickButton:) forControlEvents:UIControlEventTouchUpInside];
        [bottomView addSubview:button];
    }
    [self addSubview:bottomView];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self);
        make.bottom.equalTo(self).offset(-5);
        make.height.equalTo(@kButtonHeight);
    }];
}


//MYMARK: - ScrollView无限滚动实现逻辑
- (void)setupTimer{
    // 创建一个NSTimer定时器对象  定时为3秒触发一次
    self.timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    // 添加到NSRunLoop
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

//滚动到下一个页面
- (void)nextPage{
    CGFloat offsetX = self.scrollView.contentOffset.x + kScreenSize.width;
    [self.scrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
}

//当ScrollView被手动拖拽时，使Timer无效
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.timer invalidate];
    self.timer = nil;
}

//在手动拖拽结束时再次定制Timer
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self setupTimer];
}

// 手动滚动状态下当滚动停止的时候，偷偷的滚回对应的位置
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    [self scrollViewGoBack:scrollView];
}

// 自动动画滚动状态下当滚动停止的时候，偷偷的滚回对应的位置
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    
    [self scrollViewGoBack:scrollView];
}

/*  封装滚回响应位置的方法  */
- (void)scrollViewGoBack:(UIScrollView *)scrollView {
    
    if (scrollView.contentOffset.x == (kScreenSize.width * (kPageCount + 1))){// 滚动到了最后一个图片框
        // 让scrollView悄悄地滚动到第二个图片框
        [self.scrollView setContentOffset:CGPointMake(kScreenSize.width, 0)];
        
    }else if (scrollView.contentOffset.x == 0){
        // 让scrollView悄悄地滚动到倒数第二个图片框（第五个）
        [self.scrollView setContentOffset:CGPointMake(kScreenSize.width * kPageCount, 0)];
    }
}

// 实时计算页码
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    int index = round(scrollView.contentOffset.x / kScreenSize.width - 1);
    if (index == kPageCount) {
        index = 0;
    }else if (index == -1){
        index = kPageCount - 1;
    }
    self.pageControl.currentPage = index;
}

//移除定时
- (void)dealloc {
    
    [self.timer invalidate];
}

//MYMARK: - button的监听点击事件
- (void)didClickButton:(UIButton *)sender {
    IconsAndActivitiesModel *model = self.iconData[sender.tag];
    if (self.descBlock) {
        self.descBlock(model);
    }
}

//MYMARK: - 数据处理
- (void)setIconData:(NSArray<IconsAndActivitiesModel *> *)iconData {
    
    _iconData = iconData;
    [self.bottomView.subviews enumerateObjectsUsingBlock:^(__kindof  IconButton* _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj setTitle:iconData[idx].name forState:UIControlStateNormal];
        [obj sd_setImageWithURL:[NSURL URLWithString:iconData[idx].img] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"icon_icons_holder"]];
    }];
}

- (void)setAdData:(NSArray<IconsAndActivitiesModel *> *)adData {
    
    _adData = adData;
    if (adData.count > 0) {
        [self.scrollView.subviews enumerateObjectsUsingBlock:^(__kindof UIImageView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (idx == 0) {
                [obj sd_setImageWithURL:[NSURL URLWithString:adData[kPageCount-1].img]];
            } else if (idx == 6) {
                [obj sd_setImageWithURL:[NSURL URLWithString:adData[0].img]];
            } else {
                [obj sd_setImageWithURL:[NSURL URLWithString:adData[idx - 1].img]];
            }
        }];
    }
    [self layoutIfNeeded];
}

@end
